import { Directive, AfterViewChecked, ElementRef, OnInit, OnDestroy, NgZone } from '@angular/core';
import { DxDataGridComponent } from 'devextreme-angular/ui/data-grid';

import { ViewMainComponent } from '../view/view-main/view-main.component';
import { LoggerService } from '../../core/service/logger.service';
import { useResizeObserver } from '../../util';

@Directive({
  selector: '[bzAutoHeight]'
})
export class AutoHeightDirective<U, B, S> implements AfterViewChecked, OnInit, OnDestroy {

  private lastPanelContainerHeight = 0;
  private lastViewMainHeight = 0;
  private panelContainerEle: Element;
  private viewMainEle: Element;
  private isWatch = true;
  private resizeObserver;
  private avoidRepeatUpdate = 0;

  constructor(
    private viewMainComponent: ViewMainComponent<U, B, S>,
    private dxDataGridComponent: DxDataGridComponent,
    private elementRef: ElementRef,
    private loggerService: LoggerService,
    private zone: NgZone
  ) { }

  ngOnInit(): void {
    // if (!this.dxDataGridComponent || !this.viewMainComponent) {
    //   this.isWatch = false;
    //   this.loggerService.warn(' bz-view-main and dx-data-grid must exist', 'AutoHeightDirective');
    //   return;
    // }
    // this.viewMainEle = this.viewMainComponent.ele.nativeElement;
    // this.panelContainerEle = this.viewMainEle.querySelector('.panel-container');

    // setTimeout(() => {
    //   this.viewMainComponent.bzShowFooter = false;
    // });

    // if (useResizeObserver) {
    //   this.resizeObserver = new (<any>window).ResizeObserver(this.updateHeight.bind(this));
    //   this.resizeObserver.observe(this.panelContainerEle, { box: 'border-box' });
    //   this.resizeObserver.observe(this.viewMainEle, { box: 'border-box' });
    // }
  }

  ngAfterViewChecked(): void {
    // if (this.isWatch && !useResizeObserver && (this.lastPanelContainerHeight !== this.panelContainerEle.clientHeight || this.lastViewMainHeight !== this.viewMainEle.clientHeight)) {
    //   this.updateHeight();
    // }
  }

  updateHeight(target?: HTMLElement) {
    if (this.avoidRepeatUpdate > 1) {
      this.avoidRepeatUpdate = 0;
      return;
    }

    const diffHeight = this.viewMainEle.clientHeight - this.panelContainerEle.clientHeight;
    this.dxDataGridComponent.instance.option('height', this.elementRef.nativeElement.clientHeight + diffHeight);
    this.lastPanelContainerHeight = this.panelContainerEle.clientHeight;
    this.lastViewMainHeight = this.viewMainEle.clientHeight;
    this.avoidRepeatUpdate++;
    this.zone.runOutsideAngular(() => {
      setTimeout(() => {
        this.avoidRepeatUpdate = 0;
      }, 300);
    });
  }

  ngOnDestroy(): void {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  }
}
